/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.ShopCompany;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.dao.ShopCompanyMapper;
import com.yami.shop.service.ShopCompanyService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author lth
 * @Date 2021/8/3 16:16
 */
@Service
@AllArgsConstructor
public class ShopCompanyServiceImpl extends ServiceImpl<ShopCompanyMapper, ShopCompany> implements ShopCompanyService {

    private final ShopCompanyMapper shopCompanyMapper;

    @Override
    public void saveInfo(ShopCompany shopCompany) {
        this.checkInfo(shopCompany, true);
        save(shopCompany);
    }

    @Override
    public void updateByShopId(ShopCompany shopCompany) {
        this.checkInfo(shopCompany, false);
        saveOrUpdate(shopCompany, Wrappers.lambdaUpdate(ShopCompany.class).eq(ShopCompany::getShopId, shopCompany.getShopId()));
    }

    /**
     * 校验店铺工商信息，isCreate为true代表校验新增时的信息，false代表校验更新时的信息
     * @param shopCompany
     * @param isCreate
     */
    private void checkInfo(ShopCompany shopCompany, Boolean isCreate) {
        ShopCompany creditCodeObj = shopCompanyMapper.selectOne(Wrappers.lambdaQuery(ShopCompany.class).eq(ShopCompany::getCreditCode, shopCompany.getCreditCode()));
        if (Objects.nonNull(creditCodeObj)) {
            if (isCreate || !Objects.equals(shopCompany.getShopId(), creditCodeObj.getShopId())) {
                throw new YamiShopBindException("yami.shop.company.credit.code.repeat");
            }
        }
        if (Objects.isNull(shopCompany.getStartTime()) || Objects.isNull(shopCompany.getEndTime())) {
            throw new YamiShopBindException("yami.shop.company.date.not.empty");
        }
        if (!shopCompany.getStartTime().before(shopCompany.getEndTime())) {
            throw new YamiShopBindException("yami.shop.business.date.error");
        }
    }
}
